package com.peanut.huibutie.common;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * AES 加密
 */
@Slf4j
public class AesEncryptUtil {

    /**
     * AES加密
     *
     * @param content
     * @return
     */
    public static String encrypt(String content, String encryptKey) {
        try {
            //生成和mysql一直的加密数据
            SecretKeySpec key = generateAesKey(encryptKey, StandardCharsets.UTF_8);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);

            byte[] cleartext = content.getBytes(StandardCharsets.UTF_8);
            byte[] ciphertextBytes = cipher.doFinal(cleartext);
            return Hex.encodeHexString(ciphertextBytes).toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            log.error("AesEncryptUtil.encrypt 加密失败， content={}", content, e);
        } catch (NoSuchPaddingException e) {
            log.error("AesEncryptUtil.encrypt 加密失败， content={}", content, e);
        } catch (InvalidKeyException e) {
            log.error("AesEncryptUtil.encrypt 加密失败， content={}", content, e);
        } catch (IllegalBlockSizeException e) {
            log.error("AesEncryptUtil.encrypt 加密失败， content={}", content, e);
        } catch (BadPaddingException e) {
            log.error("AesEncryptUtil.encrypt 加密失败， content={}", content, e);
        } catch (Exception e) {
            log.error("AesEncryptUtil.encrypt 加密异常， content={}", content, e);
        }

        return null;
    }

    /**
     * AES解密
     *
     * @param content
     * @return
     */
    public static String decrypt(String content, String encryptKey) {
        try {
            SecretKey key = generateAesKey(encryptKey, StandardCharsets.UTF_8);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] cleartext = Hex.decodeHex(content.toCharArray());
            byte[] ciphertextBytes = cipher.doFinal(cleartext);
            return new String(ciphertextBytes, StandardCharsets.UTF_8);
        } catch (NoSuchAlgorithmException e) {
            log.error("AesEncryptUtil.decrypt 解密失败， content={}", content, e);
        } catch (NoSuchPaddingException e) {
            log.error("AesEncryptUtil.decrypt 解密失败， content={}", content, e);
        } catch (InvalidKeyException e) {
            log.error("AesEncryptUtil.decrypt 解密失败， content={}", content, e);
        } catch (IllegalBlockSizeException e) {
            log.error("AesEncryptUtil.decrypt 解密失败， content={}", content, e);
        } catch (BadPaddingException e) {
            log.error("AesEncryptUtil.decrypt 解密失败， content={}", content, e);
        } catch (DecoderException e) {
            log.error("AesEncryptUtil.decrypt 解密失败， content={}", content, e);
        } catch (Exception e) {
            log.error("AesEncryptUtil.decrypt 解密异常， content={}", content, e);
        }

        return null;
    }

    public static SecretKeySpec generateAesKey(final String key, Charset encoding) {
        final byte[] finalKey = new byte[16];
        int i = 0;
        for (byte b : key.getBytes(encoding))
            finalKey[i++ % 16] ^= b;
        return new SecretKeySpec(finalKey, "AES");
    }


    /**
     * 测试
     */
    public static void main(String[] args) throws Exception {
        String text = "MyPassword123@163.com";
        String key = "13E80F176EDCA604";
        String encryptStr = encrypt(text, key);
        System.out.println("数据：" + text);
        System.out.println("加密：" + encryptStr);
        String decryptStr = decrypt(encryptStr, key);
        System.out.println("解密：" + decryptStr + "----->匹配结果=" + (decryptStr.equals(text)));
    }
}
